// tslint:disable
import { PageModalService } from './../../shared/service/page-modal-service';
import { Component, OnInit, Input, OnDestroy, ViewChild } from "@angular/core";
import { AlertController, ModalController } from "@ionic/angular";
import { throws } from "assert";
import { Subscription } from "rxjs";
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { EventService } from "src/app/shared/service/event.service";
import { HttpService } from "src/app/shared/service/http.service";
import { MessageService } from "src/app/shared/service/message.service";

@Component({
  selector: 'app-send-single',
  templateUrl: './send-single.component.html',
  styleUrls: ['./send-single.component.scss'],
})
export class SendSingleComponent implements OnInit {
  // 组件数据
  @Input() tagData: any = {};
  // 声明订阅对象
  subscription: Subscription = null;

  // 筛选及页面数据参数
  params: any = {};

  // 当前页数，默认1
  pageNo = 1;

  // size
  pageSize: number;

  // 数量
  pageTotal: number;

  listData: any;

  showName = "";
  ids: any;
  dataIndex = -1;
  checkedAll = false;
  showLoadMore = false;
  constructor(
    private appGlobalService: AppGlobalService,
    private message: MessageService,
    private http: HttpService,
    private eventService: EventService,
    private modalController: ModalController,
    public alertController: AlertController,
    public pageModalService: PageModalService
  ) { }

  ngOnInit() {

    this.addEvent();
    const that = this;
    if (this.tagData.data.submit) {
      this.params = this.tagData.data.submit;
      this.params.sessionId = localStorage.getItem("sessionId");
    }

    this.listData = this.tagData.data.data;
    this.pageSize = this.tagData.pageSize;
    this.pageTotal = this.tagData.pageTotal;

    if (!this.subscription) {
      if (this.tagData.data.submit.content && this.tagData.data.submit.content.showName) {
        sessionStorage.setItem("showName", this.tagData.data.submit.content.showName);
      } else {
        sessionStorage.removeItem('showName');
      }
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {
        if (param) {
          this.showName = param.showName;
          // // 重置当前页数
          this.pageNo = 1;
          // 参数
          this.params.content = param || {};
          // 页面数据参数
          this.params.content.pageNo = this.pageNo;
          // 请求获取新数据
          this.http.post(
            "application/submit",
            this.params,
            res => {
              // 请求数据成功
              if (res.success && res.data.data && res.data.data.length > 0) {
                this.listData = res.data.data;
                console.log('this.listData:' + this.listData,);
              } else {
                this.listData = [];
                // this.appGlobalService.showToast(res.message, 2000, "middle");
              }
              // that.content.scrollToBottom(0);
            },
            err => {
              // 请求数据失败
              this.appGlobalService.showToast(err.message, 2000, "middle");
            }
          );
        }
      });
    }
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
  }
  addEvent() {
    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      console.log(res);
      const ids = [];
      this.listData.forEach(element => {
        if (element.check === 'true' && element.checked) {
          ids.push(element.id);
        }
      });
      if (ids.length === 0 && !res.noNeedChoose) {
        this.ids = '';
        return;
      } else {
        this.ids = ids.join(',');
      }
      if (res.target) {
        this.showModal(res);
      } else {
        // submit
        this.presentAlertWithMsgBtn(res, false);
      }
    });
    // 全选
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        this.checkedAll = true;
        this.listData.forEach(element => {
          if (element.check === 'true') {
            element.checked = true;
          }
        });
      } else {
        this.listData.forEach(element => {
          if (element.check === 'true') {
            element.checked = false;
          }
        });
      }
    });
  }

  ngOnDestroy(): void {
    // 组件生命周期结束的时候，注销
    this.subscription.unsubscribe();
  }
  // 上滑加载
  loadMoreData(event) {
    if (this.pageNo >= this.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    // // 请求下一个页面
    this.pageNo = this.pageNo + 1;
    // // 参数
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.http.post(
      "application/submit",
      this.params,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.listData.push(item);
              this.checkAll();
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }

  action(event, btn, dataIndex) {
    this.ids = this.listData[dataIndex].id;
    this.dataIndex = dataIndex;
    console.log(dataIndex);
    if (btn.submit) {
      this.presentAlertWithMsgBtn(btn.submit, true);
    } else if (btn.link) {
      if (btn.link.type === 'pageModal') {
        this.showModal(btn.link);
      } else if (btn.link.type === 'page') {
        this.appGlobalService.openPage(btn.link);
      }
    }

    event.stopPropagation();

  }
  openPage(event, link) {
    event.stopPropagation();
    this.appGlobalService.openPage(link);
  }
  showModal(link) {
    const that = this;
    link.params.id = this.ids;
    //  link.modalCss = 'auto-modal';
    this.pageModalService.openPage(link, '', result => {
      if (result) {
        //  that.updateItem();
      }
    })
  }

  updateItem() {
    if (this.checkedAll) {
      this.appGlobalService.reloadCurrentPage();
      return;
    }
    const that = this;
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {};
    }
    page.params.id = this.ids;
    this.http.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'sendSingleTag' && element.data && element.data.data) {
          element.data.data.forEach(newItem => {
            that.tagData.data.data.forEach(oItem => {
              if (oItem.id === newItem.id) {
                const index = that.tagData.data.data.indexOf(oItem);
                that.tagData.data.data.splice(index, 1, newItem)//替换
              }
            });
          });
        }
        that.checkAll();

      });
    });
  }
  async presentAlertWithMsgBtn(submit, needUpdate) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {

            if (submit.content.listKey){
              submit.content[submit.content.listKey] = this.ids;
            } else {
              submit.content.id = this.ids;
            }
            
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.http.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                if(submit.content.needDel){
                  that.tagData.data.data.splice(that.dataIndex, 1)
                } else
                if (needUpdate) {
                  that.updateItem();
                }
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }
  chooseClick(item) {
    if (item.check === 'true') {
      item.checked = !item.checked;
    }
    this.checkAll();
  }

  // 检查是否已经全选
  checkAll() {
    let all = true;
    try {
      this.listData.forEach(element => {
        if (element.check === 'true' && !element.checked) {
          all = false;
          this.eventService.eventEmit.emit('chooseAllResult', all);
          throw new Error('break');
        }
      });
      this.checkedAll = all;
      this.eventService.eventEmit.emit('chooseAllResult', all);
    } catch (error) {
      if (error.message !== "break") { throw error; }
    }

  }

}
